let path = require('path');
let fse = require('fs-extra');
let nunjucks = require('nunjucks');
let cheerio = require('cheerio');
let url = require('url');
let {
  minify
} = require('html-minifier');

let Tools = require('../../tools');
let {
  projectModel
} = require('../../service');

module.exports = {
  deleteProject({uuid, isDelDir}) {
    let projectInfo = projectModel.findProjectInfo({
      uuid: uuid
    });
    // 项目未发布或强制删除，直接删除文件夹、数据项
    if(isDelDir || !projectInfo['publish']){
      // 删除文件数据
      let reourceWithDir = Tools.getSourceRoot(uuid);
      fse.removeSync(reourceWithDir);
      // 删除数据库数据
      projectModel.deleteProject({uuid});
      return;
    }
    // 修改数据库数据
    projectInfo['status'] = 0;
    projectModel.update({
      uuid: uuid
    }, projectInfo);
  },
  toSaveStyle({uuid, fileTmpPath, toSavePth}) {
    console.log(fileTmpPath, toSavePth);
    fse.moveSync(fileTmpPath, toSavePth);
  },
  publishByContent ({uuid, pathDIR, styleTagsPath, req}) {
    let publishPath = Tools.getPublishPath(uuid), resourcePath = Tools.getSourceRoot();
    let sourceContent = fse.readFileSync(pathDIR, 'utf8');
    let styleTags = fse.readFileSync(styleTagsPath, 'utf8');
    let projectInfo = projectModel.findProjectInfo({
      uuid: uuid
    });
    // 完整html
    let renderHtmlStr = nunjucks.render(path.resolve('views', 'template/default.html'), {
      projectInfo,
      styleTags,
      sourceContent
    });
    // 提取 image src
    let $ = cheerio.load(renderHtmlStr), attrKeyMap = {'img': 'src', 'a': 'href', 'link': 'href'},
    baseViewURLObj = url.parse(req.fullURL), tmp;
    // 获取内同中链接，及文件地址
    let srcList = $('[src], [href]').map((idx, item) => {
      let $item = $(item), attrKey = attrKeyMap[$item.get(0).tagName];
      let srcItem = $item.attr(attrKey);
      tmp = url.parse(srcItem);
      /* 是否为全路径 */
      if(!!tmp.host){
        // 是否为本地地址
        if(['localhost','127.0.0.1'].indexOf(tmp.hostname) >= 0 || tmp.host === baseViewURLObj.host){
          srcItem = tmp.pathname.replace(global.editorPreviewPath, '');// global.editorPreviewPath
          srcItem = srcItem.replace(global.editorPath, '');
          if(srcItem[0] === '/') {
            srcItem = srcItem.substr(1);
          }
        } else {
          // 远程地址就原样输出
          return;
        }
      } else {
        srcItem = srcItem.replace(global.editorPath, '');
        if(srcItem[0] === '/') {
          srcItem = srcItem.substr(1);
        }
      }
      $item.attr(attrKey, srcItem);
      return srcItem;
    });
    // 返回处理过的html-str
    renderHtmlStr = $.html();
    // 处理压缩 html
    renderHtmlStr = minify(renderHtmlStr, {
      removeComments: true,
      collapseWhitespace: true,
      minifyJS: true,
      minifyCSS: true
    });
    /* 保存 index.html 、static资源 */
    fse.outputFileSync(publishPath + '/index.html', renderHtmlStr);
    // static
    for(let i = 0; i < srcList.length; i++){
      let fromPath = path.join(resourcePath, srcList[i]);
      let savePath = path.join(publishPath, srcList[i]);
      if(!fse.existsSync(fromPath)) {
        // 'editor-ui'
        fromPath = path.resolve(global.editorPath.substr(1), srcList[i]);
      }
      try{
        fse.copySync(fromPath, savePath);
      } catch(e) {
        console.error(e);
      }
    }
  
    // 移动完成后修改数据库, 状态改为发布
    projectInfo['publish'] = true;
    projectModel.update({
      uuid: uuid
    }, projectInfo);
  },
  publishByHtml ({uuid, pathDIR}) {
    let publishPath = Tools.getPublishPath(uuid), resourcePath = Tools.getSourceRoot();
    let htmlContent = fse.readFileSync(pathDIR, 'utf8');
    let projectInfo = projectModel.findProjectInfo({
      uuid: uuid
    });
    console.log(htmlContent);
    // 处理压缩 html
    // htmlContent = minify(htmlContent, {
    //   removeComments: true,
    //   collapseWhitespace: true,
    //   minifyJS: true,
    //   minifyCSS: true
    // });
    // let $ = cheerio.load(htmlContent);
    // $('head').append('<meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no">');
    // // 返回处理过的html-str
    // htmlContent = $.html();
    // /* 保存 index.html 、static资源 */
    // fse.outputFileSync(publishPath + '/index.html', htmlContent);
  
    // // 发布准备完成后修改数据库, 状态改为发布
    // projectInfo['publish'] = true;
    // projectModel.update({
    //   uuid: uuid
    // }, projectInfo);
  }
}